package com.gemini.collect;

import com.gemini.collect.constraint.ListMultimap;
import com.gemini.collect.constraint.Multimap;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class ArrayListMultimap<K, V> extends ListMultimap<K, V> implements Serializable {

    private static final long serialVersionUID = 42L;


    public static Multimap<String, String> create() {
        return new ArrayListMultimap<>();
    }

    private ArrayListMultimap() {
        this(new HashMap<>());
    }

    private ArrayListMultimap(Map<K, Collection<V>> map) {
        super(map);
    }

    @Override
    public int size() {
        return entity.size();
    }

    @Override
    public boolean isEmpty() {
        return entity == null || entity.size() == 0;
    }

    @Override
    public boolean containsKey(K key) {
        return entity.containsKey(key);
    }

    @Override
    public boolean containsValue(V value) {
        Collection<Collection<V>> values = entity.values();
        for (Collection<V> vs : values) {
            if (vs.contains(value)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean containsEntry(K key, V value) {
        Collection<V> vs = entity.get(key);
        if (vs != null) {
            return vs.contains(value);
        }
        return false;
    }

    @Override
    public boolean put(K key, V value) {
        Collection<V> vs = entity.get(key);
        if (vs == null) {
            vs = createCollection();
            entity.put(key, vs);
            return vs.add(value);
        } else {
            return vs.add(value);
        }
    }

    @Override
    public Collection<V> get(K key) {
        return entity.get(key);
    }

    @Override
    public Collection<V> createCollection() {
        return new ArrayList<>();
    }
}
